
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include "kernel_list.h"

struct clientinfo
{
    int connfd;
    struct sockaddr_in addr;

    struct list_head list;
}*users; // 所有的客户

struct clientinfo *init_list(void)
{
    struct clientinfo *users = calloc(1, sizeof(struct clientinfo));
    if(users != NULL)
    {
        INIT_LIST_HEAD(&users->list);
    }
    return users;
}

struct clientinfo * new_client(int connfd, struct sockaddr_in *addr)
{
    struct clientinfo *new = calloc(1, sizeof(struct clientinfo));
    if(new != NULL)
    {
        new->connfd = connfd;
        new->addr = *addr;
        INIT_LIST_HEAD(&new->list);
    }
    return new;
}

void *routine(void *arg);

// 服务端，被动接收连接请求
int main(int argc, char const *argv[]) // ./client PORT
{
    if(argc != 2)
    {
        printf("请指定绑定端口\n");
        exit(0);
    }

    // 1，创建TCP
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    // 2，准备好服务器的地址
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    bzero(&addr, len);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(atoi(argv[1]));

    // 在实验测试阶段  重组
    // 避免地址资源IP:PORT在程序退出之后（即套接字关闭之后）被系统保留
    int on = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    // 3，绑定sockfd和地址
    if(bind(sockfd, (struct sockaddr *)&addr, len) == -1)
    {
        perror("绑定地址失败");
        exit(0);
    }

    // 4，设定监听状态
    // 第二个参数指的是同时接收连接请求的个数
    listen(sockfd, 3);

    // 准备一个客户端链表
    users = init_list();

    // 5，静静地等待客户端的请求
    while(1)
    {
        struct sockaddr_in peeraddr;
        len = sizeof(peeraddr);
        bzero(&peeraddr, len);
        int connfd = accept(sockfd, (struct sockaddr *)&peeraddr, &len);
        if(connfd > 0)
        {
            printf("有新的客户端连接：[%s:%hu]\n",
                    inet_ntoa(peeraddr.sin_addr),
                    ntohs(peeraddr.sin_port));
        }

        struct clientinfo *new = new_client(connfd, &peeraddr);
        list_add_tail(&new->list, &users->list);

        // 启动一条专门的线程，去专门处理这个新client
        pthread_t t;
        pthread_create(&t, NULL, routine, (void*)new);
    }

    return 0;
}

void *routine(void *arg)
{
    pthread_detach(pthread_self());

    struct clientinfo *client = (struct clientinfo *)arg;

    char buf[150];

    while(1)
    {
        bzero(buf, 150);
        int i = snprintf(buf, 100,"[%s:%hu]:", inet_ntoa(client->addr.sin_addr),
                            ntohs(client->addr.sin_port));
        int n = read(client->connfd, buf+i, 150-i);

        if(n == 0)
        {
            fprintf(stderr, "[%s:%hu]离开了聊天室\n",
                            inet_ntoa(client->addr.sin_addr),
                            ntohs(client->addr.sin_port));

            list_del(&client->list);
            free(client);
            break;
        }

        // 转发给其他所有人
        struct list_head *pos;
        list_for_each(pos, &client->list)
        {
            struct clientinfo *p = list_entry(pos, struct clientinfo, list);

            // 跳过发送者
            if(p->connfd == client->connfd)
                continue;
                
            write(p->connfd, buf, strlen(buf));
        }
    }  
}